using GLib;

namespace Malem {
	
	protected class ListenerObject : GLib.Object, ListenerIface {
		public JobsManager jobs {get;construct;}
		public string interfacesName {get;construct;}
		private Gee.ArrayList<string> interfaces_name;
		
		public ListenerObject(string interfacesName, JobsManager jobs) {
			this.interfacesName = interfacesName;
			this.jobs = jobs;
		}
		
		construct {
			this.jobs.onCompleted += this.on_completed_jobs;
			this.jobs.onStarted += this.on_started_jobs;
			string[] i_n = interfacesName.split(",");
			if (i_n.length>1) {
				interfaces_name = new Gee.ArrayList<string>();
				foreach(string s in i_n)
					interfaces_name.add(s);
				Malem.Util.sortArrayListByString(interfaces_name, 0, interfaces_name.size-1);
			}
		}

		private bool accepted(JobObject job) {
			if (interfaces_name == null) return job.supported_interfaces.contains(this.interfacesName);
			else return Malem.Util.isSubSetString(job.supported_interfaces, this.interfaces_name);
		}

		public string[]	getCurrentJobs()	{
			Gee.Collection<JobObject> col = this.jobs.getJobs();
			if ((col==null) || (col.size==0)) return new string[0];

			string[] ret;
			int i=0;
			Gee.ArrayList<JobObject> j = new Gee.ArrayList<JobObject>();
			foreach(JobObject job in col)
				if (this.accepted(job)) j.add(job);
			ret = new string[j.size];
			foreach(JobObject job in j) {
				ret[i] = job.dbusPath+":"+job.dbusName;
//				ret[i].dbus_path = job.dbusPath;
//				ret[i].dbus_name = job.dbusName;
				i++;
			}
			return ret;
		}

		private void on_completed_jobs(JobsManager jobs, JobObject job, bool isCompletedWithSuccess) {
			if (this.accepted(job)) this.onCompletedJob(job.dbusName, job.dbusPath, isCompletedWithSuccess);
		}

		private void on_started_jobs(JobsManager jobs, JobObject job) {
			if (this.accepted(job)) this.onStartedJob(job.dbusName, job.dbusPath);
		}
	}

}
